/**
 * 
 */
package ltu.m7011e.server.service.impl;

import java.util.Iterator;
import java.util.List;
import java.util.logging.Logger;

import ltu.m7011e.server.dao.jpa.LinkDao;
import ltu.m7011e.server.pojo.AuthorEntity;
import ltu.m7011e.server.pojo.LinkEntity;
import ltu.m7011e.server.response.author.AuthorResponse;
import ltu.m7011e.server.response.link.GetLinksAction;
import ltu.m7011e.server.response.link.LinkResponse;
import ltu.m7011e.server.service.ILinkService;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

/**
 * @author robinelmouahidine
 *
 */
public class LinkService implements ILinkService {

	private static final String GET_NEWEST_LINKS_ACTION_TAG = "getNewestLink";
	private static final String GET_TOP_LINKS_ACTION_TAG = "getTopLink";
	private static final String GET_CATEGORY_ACTION_TAG = "getCatLink";


	private static final Logger log = Logger.getLogger(LinkService.class.getName());

	private final UserService userService = UserServiceFactory.getUserService();

	private final DateCalc dateCalc = new DateCalc();
	private final LinkDao linkDao = new LinkDao();

	public GetLinksAction loadNewestLinks(int numberOfRecords,int firstResult){
		GetLinksAction response = new GetLinksAction(GET_NEWEST_LINKS_ACTION_TAG);

		List<LinkEntity> results = linkDao.getNewestLinks(numberOfRecords,firstResult);
		// TODO : Call DOA to received LinkEntity from BDD
		// MOCK - Wainting for DOA implmentation			

		if(results.size()!=0){
			Iterator stIterator=results.iterator();
			while(stIterator.hasNext()){
				LinkEntity linkDao =(LinkEntity)stIterator.next();
				response.arrayLink.add(new LinkResponse((int) linkDao.getKey().getId(),linkDao.getTheLink(), 
						linkDao.getDescription(),linkDao.getLinkCat(),dateCalc.getDateDifference(linkDao.getPostDate()),linkDao.getLikes(),
						new AuthorResponse(linkDao.getLinkAuthor().getAuthorName())));
			} 
		}

		return response;
	}

	public GetLinksAction loadNewestLinksByCat(int numberOfRecords,int firstResult,String cat){

		GetLinksAction response = new GetLinksAction(GET_CATEGORY_ACTION_TAG+cat);

		List<LinkEntity> results = linkDao.getNewestLinksByCat(numberOfRecords,firstResult,cat);

		// TODO : Call DOA to received LinkEntity from BDD
		// MOCK - Wainting for DOA implmentation			

		if(results.size()!=0){
			Iterator stIterator=results.iterator();
			while(stIterator.hasNext()){
				LinkEntity linkDao =(LinkEntity)stIterator.next();
				response.arrayLink.add(new LinkResponse((int) linkDao.getKey().getId(),linkDao.getTheLink(), 
						linkDao.getDescription(),linkDao.getLinkCat(),dateCalc.getDateDifference(linkDao.getPostDate()),linkDao.getLikes(),
						new AuthorResponse(linkDao.getLinkAuthor().getAuthorName())));
			} 
		}
		return response;
	}
	public GetLinksAction loadTopLinks(int numberOfRecords,int firstResult){
		GetLinksAction response = new GetLinksAction(GET_TOP_LINKS_ACTION_TAG);
		List<LinkEntity> results = linkDao.getTopLinks(numberOfRecords,firstResult);

		// TODO : Call DOA to received LinkEntity from BDD
		// MOCK - Wainting for DOA implmentation			

		if(results.size()!=0){
			Iterator stIterator=results.iterator();
			while(stIterator.hasNext()){
				LinkEntity linkDao =(LinkEntity)stIterator.next();
				response.arrayLink.add(new LinkResponse((int) linkDao.getKey().getId(),linkDao.getTheLink(), 
						linkDao.getDescription(),linkDao.getLinkCat(),dateCalc.getDateDifference(linkDao.getPostDate()),linkDao.getLikes(),
						new AuthorResponse(linkDao.getLinkAuthor().getAuthorName())));

			} 
		}
		return response;
	}
	/**
	 * Initialize the link received in parameter and call DAO to persist it 
	 * @param newLink
	 */
	public boolean doPost(LinkResponse newLink){
		boolean state = false;
		if ( newLink.author != null && newLink.category != null  &&
				newLink.description != null && newLink.theLink != null ){
			AuthorEntity linkAuthor;
			if ( userService.getCurrentUser() != null ){
				linkAuthor = new AuthorEntity(userService.getCurrentUser().getNickname());
			}else{
				linkAuthor = new AuthorEntity("Anonymous");
			}
			LinkEntity linkToPost = new LinkEntity(newLink.theLink, linkAuthor, newLink.category, newLink.description);
			try {
				linkDao.postLinkDao(linkToPost);
				state = true;
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return state;
	}

	/**
	 * Add a like to the like specified by Id
	 * @param linkId
	 */
	public int addLikeTo(Integer linkId){
		int state = 0;

		Key linkKey = KeyFactory.createKey("LinkEntity", linkId);

		if (userService.getCurrentUser() == null){
			state = 1;	
		} else if (linkDao.addLikeDao(linkKey ,userService.getCurrentUser().getEmail())){
			state = 2;
		}
						
		return state;
	}



}